package com.moons.uvcdemo;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.moons.uvcdemo.config.DemoConfig;

import java.io.File;
import java.io.IOException;

/**
 * 用于自定义数据库安装路径
 */
public class DatabaseContext extends ContextWrapper {
    private static final String TAG = "DatabaseContext";

    public DatabaseContext(Context base) {
        super(base);
    }



    @Override
    public File getDatabasePath(String name) {
        Log.d(TAG, "getDatabasePath: ");
        String dbDir = Environment.getExternalStorageDirectory().getPath();
        if (TextUtils.isEmpty(dbDir)) {
            Log.e(TAG, "SD卡不存在，请加载SD卡");
            return super.getDatabasePath(DemoConfig.DATABASE_NAME);
        }
        File baseFile = new File(DemoConfig.DatabasePath);
        // 目录不存在则自动创建目录
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }

        File dbfile = new File(DemoConfig.DatabasePath, DemoConfig.DATABASE_NAME);
        if (!dbfile.exists()) {
            try {
                dbfile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.d(TAG, "getDatabasePath: " + dbfile.getAbsolutePath());
        return dbfile;

    }

    /**
     * 重载这个方法，是用来打开SD卡上的数据库的，android 2.3及以下会调用这个方法。
     *
     * @param name
     * @param mode
     * @param factory
     */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
        return result;
    }

    /**
     * Android 4.0会调用此方法获取数据库。
     *
     * @param name
     * @param mode
     * @param factory
     * @param errorHandler
     * @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String, int,
     * android.database.sqlite.SQLiteDatabase.CursorFactory,
     * android.database.DatabaseErrorHandler)
     */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);

        return result;
    }
}
